import { useState, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { toast } from 'sonner';
import { useTheme } from '@/hooks/useTheme';
import { base64Encode, base64Decode, md5Hash } from '@/lib/utils';

type EncoderType = 'base64' | 'md5';
type ActionType = 'encode' | 'decode';

export default function EncoderDecoder() {
  const { isDark } = useTheme();
  
  // 输入输出状态
  const [inputValue, setInputValue] = useState('');
  const [outputValue, setOutputValue] = useState('');
  
  // 加密解密类型和动作
  const [encoderType, setEncoderType] = useState<EncoderType>('base64');
  const [actionType, setActionType] = useState<ActionType>('encode');
  
  // 历史记录
  const [history, setHistory] = useState<Array<{input: string, output: string, timestamp: number}>>([]);
  const STORAGE_KEY = 'encoder_decoder_history';
  const MAX_HISTORY_COUNT = 10;
  
  // 引用
  const outputRef = useRef<HTMLTextAreaElement>(null);
  
  // 初始化时加载历史记录
  useState(() => {
    try {
      const savedHistory = localStorage.getItem(STORAGE_KEY);
      if (savedHistory) {
        setHistory(JSON.parse(savedHistory));
      }
    } catch (error) {
      console.error('加载历史记录失败:', error);
    }
  });
  
  // 保存历史记录到localStorage
  const saveHistory = (newHistory: Array<{input: string, output: string, timestamp: number}>) => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(newHistory));
      setHistory(newHistory);
    } catch (error) {
      console.error('保存历史记录失败:', error);
    }
  };
  
  // 添加到历史记录
  const addToHistory = (input: string, output: string) => {
    const newRecord = {
      input,
      output,
      timestamp: Date.now()
    };
    
    // 移除重复记录并限制数量
    const updatedHistory = [newRecord, ...history.filter(item => item.input !== input)].slice(0, MAX_HISTORY_COUNT);
    saveHistory(updatedHistory);
  };
  
  // 清除历史记录
  const clearHistory = () => {
    if (confirm('确定要清除所有历史记录吗？')) {
      saveHistory([]);
      toast.success('历史记录已清除');
    }
  };
  
  // 执行加密解密操作
  const executeAction = () => {
    if (!inputValue.trim()) {
      toast.warning('请输入内容后再进行操作');
      return;
    }
    
    try {
      let result = '';
      
      if (encoderType === 'base64') {
        if (actionType === 'encode') {
          result = base64Encode(inputValue);
        } else {
          result = base64Decode(inputValue);
        }
      } else if (encoderType === 'md5') {
        // MD5只有加密操作
        result = md5Hash(inputValue);
      }
      
      setOutputValue(result);
      addToHistory(inputValue, result);
      toast.success('操作成功完成');
    } catch (error: any) {
      toast.error(error.message || '操作失败，请检查输入');
    }
  };
  
  // 复制结果
  const copyToClipboard = async () => {
    if (!outputValue) {
      toast.warning('没有可复制的内容');
      return;
    }
    
    try {
      await navigator.clipboard.writeText(outputValue);
      toast.success('内容已复制到剪贴板');
    } catch (error) {
      toast.error('复制失败，请手动选择复制');
    }
  };
  
  // 清空输入输出
  const clearAll = () => {
    setInputValue('');
    setOutputValue('');
  };
  
  // 格式化日期时间
  const formatDateTime = (timestamp: number) => {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };
  
    return (
      <>
        <div className={`w-full p-6 sm:p-8 rounded-2xl shadow-lg ${isDark ? 'bg-gray-800' : 'bg-white'} transition-colors duration-300 mb-6`}>
          <h2 className="text-xl sm:text-2xl font-medium mb-6 text-center">
            在线加密解密工具
          </h2>
          
          {/* 功能选择 */}
          <div className="mb-8">
            <div className="flex flex-wrap gap-3 mb-4">
              <button
                onClick={() => setEncoderType('base64')}
                className={`px-4 py-2 rounded-lg transition-colors ${
                  encoderType === 'base64' 
                    ? 'bg-blue-500 text-white' 
                    : isDark 
                      ? 'bg-gray-700 text-gray-300 hover:bg-gray-600' 
                      : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                Base64
              </button>
              
              <button
                onClick={() => {
                  setEncoderType('md5');
                  setActionType('encode'); // MD5只有加密
                }}
                className={`px-4 py-2 rounded-lg transition-colors ${
                  encoderType === 'md5' 
                    ? 'bg-blue-500 text-white' 
                    : isDark 
                      ? 'bg-gray-700 text-gray-300 hover:bg-gray-600' 
                      : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                MD5
              </button>
            </div>
            
            {/* 动作选择（仅Base64显示） */}
            {encoderType === 'base64' && (
              <div className="flex flex-wrap gap-3">
                <button
                  onClick={() => setActionType('encode')}
                  className={`px-4 py-2 rounded-lg transition-colors ${
                    actionType === 'encode' 
                      ? 'bg-green-500 text-white' 
                      : isDark 
                        ? 'bg-gray-700 text-gray-300 hover:bg-gray-600' 
                        : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
                >
                  <i className="fa-lock mr-1"></i> 加密
                </button>
                
                <button
                  onClick={() => setActionType('decode')}
                  className={`px-4 py-2 rounded-lg transition-colors ${
                    actionType === 'decode' 
                      ? 'bg-orange-500 text-white' 
                      : isDark 
                        ? 'bg-gray-700 text-gray-300 hover:bg-gray-600' 
                        : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
                >
                  <i className="fa-unlock mr-1"></i> 解密
                </button>
              </div>
            )}
          </div>
          
          {/* 输入输出区域 */}
          <div className="space-y-6">
            {/* 输入区域 */}
            <div>
              <label 
                htmlFor="input-area" 
                className={`block text-sm font-medium mb-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}
              >
                {encoderType === 'base64' 
                  ? (actionType === 'encode' ? '输入需要加密的文本' : '输入需要解密的Base64字符串')
                  : '输入需要计算MD5的文本'
                }
              </label>
              <textarea
                id="input-area"
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                placeholder={encoderType === 'base64' 
                  ? (actionType === 'encode' ? '请输入需要加密的文本内容...' : '请输入需要解密的Base64字符串...')
                  : '请输入需要计算MD5的文本内容...'
                }
                className={`w-full p-4 h-32 sm:h-40 rounded-xl border focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none transition-all ${
                  isDark 
                    ? 'bg-gray-700 border-gray-600 text-white placeholder-gray-400' 
                    : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400'
                }`}
              />
            </div>
            
            {/* 操作按钮 */}
            <div className="flex flex-wrap gap-3">
              <motion.button
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                onClick={executeAction}
                disabled={!inputValue.trim()}
                className={`flex items-center gap-2 px-5 py-2.5 rounded-lg transition-colors ${
                  inputValue.trim()
                    ? 'bg-blue-500 hover:bg-blue-600 text-white'
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                }`}
              >
                <i className="fa-play"></i>
                {encoderType === 'base64' 
                  ? (actionType === 'encode' ? '执行加密' : '执行解密')
                  : '计算MD5'
                }
              </motion.button>
              
              <motion.button
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                onClick={clearAll}
                className={`flex items-center gap-2 px-5 py-2.5 rounded-lg transition-colors ${
                  isDark 
                    ? 'bg-gray-700 hover:bg-gray-600 text-white' 
                    : 'bg-gray-100 hover:bg-gray-200 text-gray-800'
                }`}
              >
                <i className="fa-trash"></i>
                清空
              </motion.button>
            </div>
            
            {/* 输出区域 */}
            {outputValue && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3 }}
                className={`p-5 rounded-xl ${isDark ? 'bg-gray-700' : 'bg-gray-50'} transition-colors duration-300`}
              >
                <div className="flex items-center justify-between mb-2">
                  <label 
                    htmlFor="output-area" 
                    className={`block text-sm font-medium ${isDark ? 'text-gray-300' : 'text-gray-600'}`}
                  >
                    {encoderType === 'base64' 
                      ? (actionType === 'encode' ? '加密结果' : '解密结果')
                      : 'MD5结果'
                    }
                  </label>
                  
                  <button
                    onClick={copyToClipboard}
                    className={`p-1.5 rounded-lg transition-colors ${
                      isDark 
                        ? 'bg-gray-600 hover:bg-gray-500 text-gray-200' 
                        : 'bg-white hover:bg-gray-200 text-gray-700 shadow-sm'
                    }`}
                  >
                    <i className="fa-copy"></i>
                  </button>
                </div>
                
                <textarea
                  ref={outputRef}
                  id="output-area"
                  value={outputValue}
                  readOnly
                  className={`w-full p-4 h-32 sm:h-40 rounded-xl border ${
                    isDark 
                      ? 'bg-gray-800 border-gray-600 text-white' 
                      : 'bg-white border-gray-200 text-gray-800'
                  }`}
                />
              </motion.div>
            )}
            
            {/* 历史记录 */}
            {history.length > 0 && (
              <div className="mt-8">
                <div className="flex items-center justify-between mb-4">
                  <h3 className={`text-lg font-medium ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
                    操作历史
                  </h3>
                  
                  <button
                    onClick={clearHistory}
                    className={`text-sm flex items-center gap-1 ${
                      isDark ? 'text-red-400 hover:text-red-300' : 'text-red-500 hover:text-red-600'
                    }`}
                  >
                    <i className="fa-trash-can"></i>
                    清除历史
                  </button>
                </div>
                
                <div className={`max-h-60 overflow-y-auto rounded-xl border ${
                  isDark ? 'border-gray-700' : 'border-gray-200'
                }`}>
                  {history.map((item, index) => (
                    <motion.div
                      key={index}
                      initial={{ opacity: 0, x: -10 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ duration: 0.2, delay: index * 0.05 }}
                      className={`p-3 border-b ${
                        isDark 
                          ? 'border-gray-700 hover:bg-gray-700' 
                          : 'border-gray-100 hover:bg-gray-50'
                      }`}
                    >
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-xs font-medium text-blue-500">
                          {formatDateTime(item.timestamp)}
                        </span>
                        <div className="flex items-center gap-1">
                          <button
                            onClick={() => setInputValue(item.input)}
                            className={`text-xs p-1 rounded ${
                              isDark ? 'hover:bg-gray-600' : 'hover:bg-gray-200'
                            }`}
                            title="使用此输入"
                          >
                            <i className="fa-arrow-up"></i>
                          </button>
                          <button
                            onClick={() => {
                              setOutputValue(item.output);
                              copyToClipboard();
                            }}
                            className={`text-xs p-1 rounded ${
                              isDark ? 'hover:bg-gray-600' : 'hover:bg-gray-200'
                            }`}
                            title="复制结果"
                          >
                            <i className="fa-copy"></i>
                          </button>
                        </div>
                      </div>
                      <div className="text-sm truncate">{item.input}</div>
                    </motion.div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
        
        {/* 功能说明 */}
        <div className={`mt-6 p-4 rounded-lg ${isDark ? 'bg-gray-800' : 'bg-white'} shadow-sm transition-colors duration-300`}>
          <h3 className="text-lg font-medium mb-3 text-center">功能说明</h3>
          <ul className="space-y-2">
            <li className="flex items-start gap-2">
              <i className="fa-check-circle text-green-500 mt-0.5"></i>
              <span className="text-sm">支持Base64加密和解密操作</span>
            </li>
            <li className="flex items-start gap-2">
              <i className="fa-check-circle text-green-500 mt-0.5"></i>
              <span className="text-sm">支持计算文本的MD5哈希值</span>
            </li>
            <li className="flex items-start gap-2">
              <i className="fa-check-circle text-green-500 mt-0.5"></i>
              <span className="text-sm">自动保存操作历史，方便重复使用</span>
            </li>
            <li className="flex items-start gap-2">
              <i className="fa-check-circle text-green-500 mt-0.5"></i>
              <span className="text-sm">所有操作均在本地进行，保障数据安全</span>
            </li>
          </ul>
        </div>
      </>
    );
}